﻿#region COPYRIGHT
//--------------------------------------------------------------------------------
// <copyright file="SpatialFiniteHash.cs" company="starLiGHT Entertainment Studios">
//    Copyright (c) 2010, 2011
//       Roland Rosenkranz (Glatzemann@email.de)
// </copyright>
// <license>
//   This file is part of starLiGHT.Collision.
//
//   starLiGHT.Collision is free software: you can redistribute it and/or modify
//   it under the terms of the GNU Lesser General Public License as published by
//   the Free Software Foundation, either version 3 of the License, or
//   (at your option) any later version.
//
//   starLiGHT.Collision is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU Lesser General Public License for more details.
//
//   You should have received a copy of the GNU Lesser General Public License
//   along with starLiGHT.Collision. If not, see http://www.gnu.org/licenses/.
//    
//   ADDITIONAL (commercial) LICENSES for starLiGHT.Collision are available on request.
// </license>
// <version>
// **************[ starLiGHT.Engine SVN ]**********************
// * $Rev:: 3345                  $:  Revision of last commit *
// * $Author:: unknown            $:  Author of last commit   *
// * $Date:: 2011-01-13 16:01:08 #$:  Date of last commit     *
// ************************************************************
// </version>
//--------------------------------------------------------------------------------
#endregion

namespace starLiGHT.Collision.BroadPhase
{
    #region Using Statements
    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.Xna.Framework;
    using starLiGHT.Collections;
    #endregion

    public class SpatialFiniteHash : AbstractBroadPhase, IBroadPhase
    {
        #region Member Variables
        private int sceneWidth;
        private int sceneHeight;
        private int cellSize;
        private int cols;
        private int rows;
        private Dictionary<int, FastList<ICollidable>> buckets;
        
        #endregion

        public SpatialFiniteHash(int sceneWidth, int sceneHeight, int cellSize)
        {
            this.sceneWidth = sceneWidth;
            this.sceneHeight = sceneHeight;
            this.cellSize = cellSize;

            this.Setup(sceneWidth, sceneHeight, cellSize);
        }

        public override void BuildCollisionPairs(CollisionManager manager, ref ICollidable[] collidables)
        {
            if (collidables == null)
            {
                return;
            }

            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            ICollidable2D a;
            int j = 0;

            // *****************
            // * add new pairs *
            // *****************
            TestCount = 0;
            int collidableCount = collidables.Length;
            for (ushort i = 0; i < collidableCount; i++)
            {
                a = collidables[i] as ICollidable2D;
                if (a != null)
                {
                    foreach (ICollidable2D b in this.GetNearby(a))
                    {
                        if (b != null)
                        {
                            if (a != b && (!a.Static || !b.Static) && this.Test(a, b))
                            {
                                manager.PairManager.AddPair(i, j++, a, b);
                            }
                        }
                    }
                }
            }
        }

        public override bool Test(ICollidable2D a, ICollidable2D b)
        {
            if (a == null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == null)
            {
                throw new ArgumentNullException("b");
            }

            TestCount++;

            return a.WorldBoundingRectangle.Intersects(b.WorldBoundingRectangle);
        }

        public override bool Test(ICollidable3D a, ICollidable3D b)
        {
            throw new NotSupportedException("SpatialFiniteHash is 2D only");
        }

        public override bool CheckCompatibility(ICollidable c)
        {
            try
            {
                if (c is ICollidable2D)
                {
                    return !((ICollidable2D)c).BoundingCircle.IsEmpty;
                }
            }
            catch
            {
            }

            return false;
        }

        public override void RegisterObject(ICollidable2D c)
        {
            if (c == null)
            {
                return;
            }

            foreach (int item in this.GetIdForObj(c))
            {
                this.buckets[item].Add(c);
            }
        }

        private void Setup(int sceneWidth, int sceneHeight, int cellSize)
        {
            this.cols = sceneWidth / cellSize;
            this.rows = sceneHeight / cellSize;
            int maxObjects = this.cols * this.rows;
            this.buckets = new Dictionary<int, FastList<ICollidable>>(maxObjects);

            for (int i = 0; i < maxObjects; i++)
            {
                this.buckets.Add(i, new FastList<ICollidable>(maxObjects));
            }
        }

        private IEnumerable<int> GetIdForObj(ICollidable2D c)
        {
            Vector2 min = c.WorldBoundingRectangle.TopLeft;
            Vector2 max = c.WorldBoundingRectangle.BottomRight;

            float width = this.sceneWidth / this.cellSize;
  
            // TopLeft
            yield return this.AddBucket(min.X, min.Y, width);

            // TopRight
            yield return this.AddBucket(max.X, min.Y, width);

            // BottomRight
            yield return this.AddBucket(max.X, max.Y, width);

            // BottomLeft
            yield return this.AddBucket(min.X, max.Y, width);
        }

        private int AddBucket(float x, float y, float width)
        {
            return (int)(Math.Floor(x / this.cellSize) + (Math.Floor(y / this.cellSize) * width));
        }

        private IEnumerable<ICollidable2D> GetNearby(ICollidable2D c)
        {
            foreach (int objId in this.GetIdForObj(c))
            {
                for (int i = 0; i < this.buckets[objId].Count; i++)
                {
                    yield return this.buckets[objId][i] as ICollidable2D;
                }
            }
        }
    }
}
